/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.interceptor;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.jrose.api.annotation.cache.CacheSupport;
import org.jrose.core.cache.CachePolicy;
import org.jrose.core.cache.CurrentCachePolicy;
import org.jrose.core.cache.UseCachePolicy;
import org.jrose.core.cache.handler.CacheMethodHandler;
import org.jrose.core.cache.handler.CacheMethodHandlerFactory;
import org.jrose.core.jdbc.datasource.RoutingPolicyCallback;
import org.jrose.core.jdbc.datasource.RoutingPolicyTemplate;
import org.jrose.core.jdbc.datasource.UseRoutingPolicy;
import org.jrose.core.util.AnnotationUtils;
import org.jrose.core.util.TargetInvoker;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Method interceptor implementation based on specified annotations.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-26 10:34
 */
@RequiredArgsConstructor
public class AnnotationMethodInterceptor implements MethodInterceptor {
    @NonNull private final ApplicationContext applicationContext;
    @NonNull private final Object target;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        final Method method = invocation.getMethod();
        final Object[] arguments = invocation.getArguments();

        // invocation on 'toString()' method
        if (AopUtils.isToStringMethod(method)) {
            return "Cache proxy for [" + target + "]";
        }

        if (method.isAnnotationPresent(UseRoutingPolicy.class)) {
            UseRoutingPolicy useRoutingPolicy = method.getAnnotation(UseRoutingPolicy.class);
            return RoutingPolicyTemplate.execute(useRoutingPolicy.value(), new RoutingPolicyCallback<Object>() {
                @Override
                public Object doInRoutingPolicy() {
                    try {
                        return invokeCacheSupportMethod(method, arguments);
                    } catch (Throwable throwable) {
                        if (throwable instanceof InvocationTargetException) {
                            throwable = ((InvocationTargetException) throwable).getTargetException();
                        }
                        if (throwable instanceof RuntimeException) {
                            throw (RuntimeException) throwable;
                        }
                        throw new RuntimeException(throwable.getMessage(), throwable);
                    }
                }
            });
        } else {
            return invokeCacheSupportMethod(method, arguments);
        }
    }

    private Object invokeCacheSupportMethod(Method method, Object[] arguments) throws Throwable {
        CachePolicy cachePolicy = currentCachePolicy(method);
        if (cachePolicy == CachePolicy.ignoringCache) {
            return TargetInvoker.of(target).invoke(method, arguments);
        }

        CacheSupport cacheSupport = AnnotationUtils.getAnnotation(target.getClass(), CacheSupport.class);
        if (cacheSupport == null || !cacheSupport.enable()) {
            // no @CacheSupport, invoke directly
            return TargetInvoker.of(target).invoke(method, arguments);
        }

        CacheManager cacheManager;
        try {
            cacheManager = applicationContext.getBean(CacheManager.class);
        } catch (BeansException ex) {
            // no CacheManager available, invoke directly
            return TargetInvoker.of(target).invoke(method, arguments);
        }

        CacheMethodHandler handler = CacheMethodHandlerFactory.build(cacheManager, cacheSupport, target, method, arguments);
        return handler.handle();
    }

    private CachePolicy currentCachePolicy(Method method) {
        if (method.isAnnotationPresent(UseCachePolicy.class)) {
            return method.getAnnotation(UseCachePolicy.class).value();
        }
        return CurrentCachePolicy.current();
    }
}
